package src; 

import java.awt.Color;
import java.util.concurrent.*;

import src.GridLocation;
import src.Player;
import src.SuperTicTacToeGame;

/**
 * Represents a HumanPlayer. Additional "name" field added on top of existing functionality inherited from Player superclass. 
 * @author Akshat, Anurag
 *
 */
public class NetworkPlayer extends Player
{
	private Semaphore lock; 
	private String name; 
	boolean local;
	private NetworkedSuperTicTacToeGame game;
	
	/**
	 * Constructor for a network player.
	 * @param n the name
	 * @param c the color
	 * @param g the game
	 * @param local if the player is local or not.
	 */
	public NetworkPlayer(String n, Color c, NetworkedSuperTicTacToeGame g, boolean local)
	{
		super(c);
		
		this.local = local;
		
		name = n;
		lock = new Semaphore(0); 
		
		game = g;
	}
	
	/**
	 * Sets the game that is associated with the object.
	 * @param g the game.
	 */
	public void setGame(NetworkedSuperTicTacToeGame g)
	{
	    game = g;
	}
	
	/**
	 * @return name of this player
	 */
	public String getName()
	{
	    return name;
	}

	/**
	 * LOCKED UNTIL setPlay is called (in Game after location clicked on GUI)
	 */
	public GridLocation getPlay()
	{
	        try
	        {
	            lock.acquire();
	            return playLoc; 
	        }
	        catch( InterruptedException e )
	        {
	            throw new RuntimeException("FATAL INTERRUPTION EXCEPTION");
	        } 
		
	}
	
	/** 
	 * Called by the Game after the GUI has been clicked. Allows for getPlay() to be called once, which allows Player to Play() once
	 * allowing game to progress. 
	 * @param loc where to set play
	 */
	public void setPlay(GridLocation loc)
	{
	        lock.drainPermits();
	        playLoc = loc; 
	        lock.release();
	   
		
	}
	
	/** (non-Javadoc)
	 * @see src.Player#play()
	 * Override to make the game repaint.
	 */
	public void play()
    {
        GridLocation loc = getPlay(); 
        
        game.controller.repaintGUI();
        game.getBoard().placePiece(new GamePiece(color, loc), loc); 
        game.controller.repaintGUI();
        
    }
	
	/**
	 * Returns the location of the player either local (true) or remote (false)
	 * @return boolean local
	 */
	public boolean getLocal()
	{
	    return local;
	}

	/** (non-Javadoc)
	 * @see src.Player#toString()
	 * @return the name of the player
	 */
	@Override
	public String toString() 
	{
		return getName();
	}
	
	
	
}
